<template>
	<mescroll-uni @init="mescrollInit" :up="upOption" :down="downOption" @down="downCallback" @up="upCallback">
		<view class="search-bar">
			<view class="search-container">
				<picker class="filter-picker" @change="queryChange" :range="queryList" range-key="queryName">
					<view class="picker-content">
						<image class="filter-icon" src="/static/filter.png"></image>
					</view>
				</picker>

				<view class="search-input">
					<input v-model="searchForm.shangpinmingcheng" placeholder="搜索商品名称" class="search-field"
						placeholder-class="placeholder-style" />
					<view class="cuIcon-search search-icon" @tap="search"></view>
				</view>

				<button v-if="roles == 'maijia'" class="add-button" @tap="showFormPopup">
					<view class="cuIcon-add"></view>
				</button>
			</view>
		</view>

		<!-- 商品列表 -->
		<view class="product-grid">
			<view class="product-card" v-for="(product, index) in list" :key="index" @tap="onDetailTap(product)">
				<!-- <image class="product-image" :src="product.tupian?.split(',')[0]" mode="aspectFill"></image> -->
				<!-- <image :class="product-image" mode="aspectFill" class="uni-product-image"
					:src="product.tupian?product.tupian.split(',')[0]:''"></image> -->
				<image mode="aspectFill" class="uni-product-image product-image"
					:src="_imgUrl + (product.tupian ? product.tupian.split(',')[0] : '')" />
				<view class="product-info">
					<text class="product-title">{{ product.shangpinmingcheng }}</text>

					<view class="action-buttons" v-if="roles == 'maijia'">
						<button class="action-btn edit" @click.stop="onUpdateTap(product)">
							<view class="cuIcon-edit"></view>
						</button>
						<button class="action-btn delete" @click.stop="onDeleteTap(product.id)">
							<view class="cuIcon-delete"></view>
						</button>
					</view>
				</view>
			</view>
		</view>

		<!-- 新增商品弹窗 -->
		<uni-popup ref="formPopup" type="bottom">
			<view class="form-popup">
				<view class="popup-header">
					<text>新增商品</text>
					<view class="cuIcon-close" @click="closeFormPopup"></view>
				</view>

				<scroll-view scroll-y class="form-content">
					<view class="form-item">
						<text class="form-label">商品名称</text>
						<input v-model="formData.shangpinmingcheng" class="form-input" />
					</view>

					<view class="form-item">
						<text class="form-label">价格</text>
						<input v-model="formData.jiage" type="number" class="form-input" />
					</view>

					<view class="form-item">
						<text class="form-label">图片上传</text>
						<view class="upload-box" @click="chooseImage">
							<image v-if="formData.tupian" :src="_imgUrl + formData.tupian" class="preview-image" />
							<uni-icons v-else type="image" size="40" color="#ccc" />
						</view>
					</view>
					<view class="form-item">
						<text class="form-label">选择农户</text>
						<picker class="address-picker" @change="nonghuChange" :range="nonghuList" range-key="nickName">
							<view class="form-label">{{ selectedNonghu || " 选择农户" }}</view>
						</picker>
					</view>
					<!-- 
					<view class="form-item">
						<text class="form-label">商品规格</text>
						<input v-model="formData.guige" class="form-input" />
					</view> -->

					<view class="form-item">
						<text class="form-label">库存数量</text>
						<input v-model="formData.shuliang" type="number" class="form-input" />
					</view>

					<view class="form-item">
						<text class="form-label">商品详情</text>
						<textarea v-model="formData.guige" class="form-textarea" />
					</view>

					<view class="form-item">
						<text class="form-label">发货地址</text>
						<input v-model="formData.dizhi" class="form-input" />
					</view>
				</scroll-view>

				<view class="form-buttons">
					<button class="form-btn cancel" @click="closeFormPopup">取消</button>
					<button class="form-btn confirm" @click="submitForm">提交</button>
				</view>
			</view>
		</uni-popup>
	</mescroll-uni>
</template>

<script>
	export default {
		data() {
			return {
				btnColor: [
					"#409eff",
					"#67c23a",
					"#909399",
					"#e6a23c",
					"#f56c6c",
					"#356c6c",
					"#351c6c",
					"#f093a9",
					"#a7c23a",
					"#104eff",
					"#10441f",
					"#a21233",
					"#503319",
				],
				queryList: [{
					queryName: "商品名称",
				}, ],
				sactiveItem: {
					padding: "0 28rpx",
					boxShadow: "0 0 12rpx rgba(0,0,0,.3)",
					margin: "0 12rpx",
					borderColor: "rgba(0,0,0,1)",
					backgroundColor: "#333",
					color: "#fff",
					borderRadius: "8rpx",
					borderWidth: "0",
					width: "auto",
					lineHeight: "68rpx",
					fontSize: "28rpx",
					borderStyle: "solid",
				},
				sitem: {
					padding: "0 20rpx",
					boxShadow: "0 0 12rpx rgba(0,0,0,.3)",
					margin: "0 12rpx",
					borderColor: "rgba(0,0,0,1)",
					backgroundColor: "#fff",
					color: "#333",
					borderRadius: "8rpx",
					borderWidth: "0",
					width: "auto",
					lineHeight: "68rpx",
					fontSize: "28rpx",
					borderStyle: "solid",
				},
				queryIndex: 0,
				list: [],
				mescroll: null, //mescroll实例对象
				downOption: {
					auto: false, //是否在初始化后,自动执行下拉回调callback; 默认true
				},
				upOption: {
					noMoreSize: 5, //如果列表已无数据,可设置列表的总数量要大于半页才显示无更多数据;避免列表数据过少(比如只有一条数据),显示无更多数据会不好看; 默认5
					textNoMore: "~ 没有更多了 ~",
				},
				hasNext: true,
				searchForm: {},
				CustomBar: "0",
				formPopupVisible: false,
				formData: {
					shangpinmingcheng: "",
					jiage: "",
					tupian: "",
					guige: "",
					shuliang: "",
					xiangqing: "",
					dizhi: "",
				},
				_imgUrl: "",
				isEdit: false,
				roles: "",
				nonghuList: [],
				selectedNonghu: null,
				pageCount: 0,
				total: 0
			};
		},
		async onShow() {
			this._imgUrl = this.$base.url;
			this.roles = uni.getStorageSync("roles");
			this.btnColor = this.btnColor.sort(() => {
				return 0.5 - Math.random();
			});
			this.hasNext = true;
			// 重新加载数据
			if (this.mescroll) this.mescroll.resetUpScroll();
		},
		onLoad() {
			this.hasNext = true;
			// 重新加载数据
			if (this.mescroll) this.mescroll.resetUpScroll();
			this.getnonghuList();
		},
		methods: {
			async getnonghuList() {
				try {
					let res = await this.$api.list1("user");
					if (res.code == 200) {
						this.nonghuList = res.rows
							.filter((item) => {
								return item.roleId == 100;
							})
							.map((item) => {
								return {
									id: item.userId,
									nickName: item.nickName,
								};
							});
						console.log("this.userList", this.nonghuList);
					}
				} catch (error) {}
			},

			nonghuChange(e) {
				this.formData.nonghuzhanghao = this.nonghuList[e.detail.value].id;
				this.formData.nonghuxingming = this.nonghuList[e.detail.value].nickName;
				this.selectedNonghu = this.nonghuList[e.detail.value].nickName;
				console.log(this.formData.nonghuzhanghao, this.formData.nonghuxingming);

			},
			//查询条件切换
			queryChange(e) {
				this.queryIndex = e.detail.value;
				this.searchForm.shangpinmingcheng = "";
			},
			//类别搜索
			// mescroll组件初始化的回调,可获取到mescroll对象
			mescrollInit(mescroll) {
				this.mescroll = mescroll;
			},
			/*下拉刷新的回调 */
			downCallback(mescroll) {
				this.hasNext = true;
				// 重置分页参数页数为1
				mescroll.resetUpScroll();
			},
			/*上拉加载的回调: mescroll携带page的参数, 其中num:当前页 从1开始, size:每页数据条数,默认10 */
			async upCallback(mescroll) {
				let params = {
					page: mescroll.num,
					limit: mescroll.size,
					remark: uni.getStorageSync("userInfo").userId,
				};

				let res = await this.$api.list(`shangpinxinxi`, params);
				this.total = res.total
				if (this.pageCount == this.total) {
					mescroll.endSuccess(mescroll.size, this.hasNext);
					return
				}
				// 如果是第一页数据置空
				if (mescroll.num == 1) this.list = [];
				this.list = this.list.concat(res.rows);
				this.pageCount = this.list.length
				if (res.rows.length == 0) this.hasNext = false;
				mescroll.endSuccess(mescroll.size, this.hasNext);
			},
			// 详情
			onDetailTap(item) {
				this.$utils.jump(`./detail?id=${item.id}`);
			},
			// 修改
			onUpdateTap(item) {
				// this.$utils.jump(`./add-or-update?id=${id}`)
				this.formPopupVisible = true;
				this.$refs.formPopup.open();
				this.isEdit = true;
				this.formData = {
					...item,
				};
			},
			// 添加
			onAddTap() {
				// this.$utils.jump(`./add-or-update`)
			},
			onDeleteTap(id) {
				var _this = this;
				uni.showModal({
					title: "提示",
					content: "是否确认删除",
					success: async function(res) {
						if (res.confirm) {
							await _this.$api.del("shangpinxinxi", id);
							_this.hasNext = true;
							// 重置分页参数页数为1
							_this.mescroll.resetUpScroll();
						}
					},
				});
			},
			// 搜索
			async search() {
				this.mescroll.num = 1;
				// let searchForm = {
				// 	page: this.mescroll.num,
				// 	limit: this.mescroll.size,
				// };
				// if (this.searchForm.shangpinmingcheng) {
				// 	searchForm["shangpinmingcheng"] =
				// 		"%" + this.searchForm.shangpinmingcheng + "%";
				// }
				let searchForm = {
					// pageNum: this.mescroll.num,
					// pageSize: this.mescroll.size,
					page: this.mescroll.num,
					limit: this.mescroll.size,
					remark: uni.getStorageSync("userInfo").userId,
				};
				if (this.searchForm.shangpinmingcheng) {
					searchForm["shangpinmingcheng"] =
							 this.searchForm.shangpinmingcheng ;
				}
				let res = await this.$api.list(`shangpinxinxi`, searchForm);
				// 如果是第一页数据置空
				if (this.mescroll.num == 1) this.list = [];
				this.list = this.list.concat(res.rows);
				if (res.rows.length == 0) this.hasNext = false;
				this.mescroll.endSuccess(this.mescroll.size, this.hasNext);
			},
			// 显示表单弹窗
			showFormPopup() {
				console.log(12132);
				this.formPopupVisible = true;
				this.$refs.formPopup.open();
				this.isEdit = false;
			},

			// 关闭表单弹窗
			closeFormPopup() {
				this.formPopupVisible = false;
				this.$refs.formPopup.close();
				this.resetForm();
			},

			// 重置表单
			resetForm() {
				this.formData = {
					shangpinmingcheng: "",
					jiage: "",
					tupian: "",
					guige: "",
					shuliang: "",
					xiangqing: "",
					dizhi: "",
				};
			},

			// 处理文件上传
			// handleFileUpload(e) {
			// 	const files = e.tempFilePaths
			// 	this.formData.tupian = files.join(',')
			// },
			async chooseImage() {
				// try {
					// #ifdef MP-WEIXIN

					// #endif
					// #ifndef MP-WEIXIN
					// const res = await uni.chooseFile({
					// 	count: 1,
					// 	type: "all",
					// });
					// #endif
					let _this = this;
					this.$api.upload(function(res) {
						console.log("123123", res);
						_this.formData.tupian = res.fileName;
						// _this.ruleForm.avatar = res.fileName;
						// _this.$forceUpdate();
					});
					// 	console.log("上传", res, res[1].tempFilePaths[0]);
					// 	uni.uploadFile({
					// 		url: "http://localhost:8080/common/upload", // 示例服务器地址
					// 		filePath: res[1].tempFilePaths[0],
					// 		name: "file",
					// 		formData: {
					// 			user: "test",
					// 		},
					// 		header: {
					// 			authorization: uni.getStorageSync("token"),
					// 		},
					// 		success: async (uploadFileRes) => {
					// 			console.log("uploadFileRes,", uploadFileRes);
					// 			this.formData.tupian = JSON.parse(uploadFileRes.data).fileName;
					// 		},
					// 	});
					// 	// const file = res.tempFiles[0];
					// 	// const fileType = getFileType(file.name);
					// 	// console.log("sh", file, fileType);
					// 	// formData.value.materialType = fileType;
					// 	uni.showToast({
					// 		title: "上传成功",
					// 		icon: "success",
					// 	});
					// } catch (error) {
					// 	uni.showToast({
					// 		title: "上传取消",
					// 		icon: "none",
					// 	});
					// }
				},

				// 提交表单
				async submitForm() {
					// 表单验证
					if (!this.formData.shangpinmingcheng) {
						return uni.showToast({
							title: "请输入商品名称",
							icon: "none",
						});
					}
					if (!this.formData.jiage || isNaN(this.formData.jiage)) {
						return uni.showToast({
							title: "请输入有效价格",
							icon: "none",
						});
					}
					if (!this.formData.tupian) {
						return uni.showToast({
							title: "请上传商品图片",
							icon: "none",
						});
					}
					this.formData.remark = uni.getStorageSync("userInfo").userId;
					if (this.isEdit) {
						try {
							// 调用API提交数据
							await this.$api.update("shangpinxinxi", this.formData);
							uni.showToast({
								title: "修改成功",
							});
							this.closeFormPopup();
							// 刷新列表数据
							this.mescroll.resetUpScroll();
						} catch (e) {
							uni.showToast({
								title: "提交失败，请重试",
								icon: "none",
							});
						}
						this.isEdit = false;
					} else {
						try {
							// 调用API提交数据
							await this.$api.add("shangpinxinxi", this.formData);
							uni.showToast({
								title: "添加成功",
							});
							this.closeFormPopup();
							// 刷新列表数据
							this.mescroll.resetUpScroll();
						} catch (e) {
							uni.showToast({
								title: "提交失败，请重试",
								icon: "none",
							});
						}
					}
				},
			},
		};
</script>

<style lang="scss" scoped>
	.search-bar {
		padding: 24rpx 32rpx;
		background: rgba(255, 255, 255, 0.95);
		backdrop-filter: blur(20rpx);
		position: sticky;
		top: 0;
		z-index: 2;
	}

	.search-container {
		display: flex;
		align-items: center;
		gap: 16rpx;

		.filter-picker {
			.filter-icon {
				width: 36rpx;
				height: 36rpx;
			}
		}
	}

	.search-input {
		flex: 1;
		background: #f8f9ff;
		border-radius: 48rpx;
		padding: 0 24rpx;
		display: flex;
		align-items: center;

		.search-field {
			flex: 1;
			font-size: 28rpx;
			color: #2d3748;
			padding: 20rpx 0;
		}

		.search-icon {
			color: #667eea;
			font-size: 36rpx;
		}
	}

	.add-button {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		background: linear-gradient(135deg, #667eea, #764ba2);
		color: white;
		display: flex;
		align-items: center;
		justify-content: center;

		.cuIcon-add {
			font-size: 40rpx;
		}
	}

	.product-grid {
		padding: 32rpx;
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 24rpx;
	}

	.product-card {
		background: rgba(255, 255, 255, 0.95);
		border-radius: 24rpx;
		overflow: hidden;
		box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.1);

		.product-image {
			width: 100%;
			height: 320rpx;
		}
	}

	.product-info {
		display: flex;
		padding: 24rpx;

		.product-title {
			font-size: 28rpx;
			color: #2d3748;
			font-weight: 500;
			line-height: 1.4;
			display: -webkit-box;
			-webkit-line-clamp: 2;
			-webkit-box-orient: vertical;
			overflow: hidden;
		}
	}

	.action-buttons {
		display: flex;
		justify-content: flex-end;
		gap: 16rpx;
		margin-top: 24rpx;

		.action-btn {
			width: 64rpx;
			height: 64rpx;
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;

			&.edit {
				background: rgba(102, 126, 234, 0.1);
				color: #667eea;
			}

			&.delete {
				background: rgba(255, 71, 87, 0.1);
				color: #ff4757;
			}
		}
	}

	.form-popup {
		background: rgba(255, 255, 255, 0.98);
		border-radius: 40rpx 40rpx 0 0;
		padding: 48rpx;

		.popup-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 48rpx;

			text {
				font-size: 36rpx;
				font-weight: 600;
				color: #2d3748;
			}

			.cuIcon-close {
				font-size: 36rpx;
				color: #718096;
				padding: 16rpx;
			}
		}
	}

	.form-content {
		height: 70vh;

		.form-item {
			margin-bottom: 32rpx;

			.form-label {
				display: block;
				color: #667eea;
				font-size: 28rpx;
				margin-bottom: 16rpx;
			}

			.form-input,
			.form-textarea {
				background: #f8f9ff;
				border-radius: 16rpx;
				padding: 24rpx;
				font-size: 28rpx;
				color: #2d3748;
			}

			.upload-box {
				width: 200rpx;
				height: 200rpx;
				border: 2rpx dashed #ccc;
				border-radius: 12rpx;
				display: flex;
				justify-content: center;
				align-items: center;

				.preview-image {
					width: 100%;
					height: 100%;
					border-radius: 8rpx;
				}
			}

			.form-textarea {
				height: 200rpx;
			}
		}
	}

	.form-buttons {
		display: flex;
		gap: 32rpx;
		margin-top: 48rpx;

		.form-btn {
			flex: 1;
			height: 88rpx;
			border-radius: 48rpx;

			&.cancel {
				background: #f1f3fe;
				color: #667eea;
			}

			&.confirm {
				background: linear-gradient(135deg, #667eea, #764ba2);
				color: white;
			}
		}
	}
</style>